﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web.UI.WebControls;
//using www.SService;
using Controllerss;
using Core.Contract.DataContract;

namespace www.Admin
{
    public partial class GrandRole : System.Web.UI.Page
    {
        #region Value
        private readonly ObjectCache _cache = MemoryCache.Default;
        //private readonly HyServicesClient _service1 = new HyServicesClient();
        private readonly MenuMemberController _menuMemberController=new MenuMemberController();
        private readonly MenuController _menuController=new MenuController();
        private readonly LoginController _loginController=new LoginController();
       
        private static long StaffId;
        #endregion

        #region Contructor

        //protected override void Render(HtmlTextWriter writer)
        //{
        //    foreach (GridViewRow row in grvnotmap.Rows)
        //    {
        //        if (row.RowType == DataControlRowType.DataRow)
        //        {
        //            row.Attributes["onmouseover"] =
        //               "this.style.cursor='pointer';";
        //            row.Attributes["onmouseout"] =
        //               "this.style.textDecoration='none';";
        //            row.Cells[0].Attributes["onclick"] =
        //             ClientScript.GetPostBackClientHyperlink(grvnotmap,
        //                "Select$" + row.DataItemIndex, true);
        //            row.Cells[1].Attributes["onclick"] =
        //             ClientScript.GetPostBackClientHyperlink(grvnotmap,
        //                "Select$" + row.DataItemIndex, true);

        //        }
        //    }
        //    foreach (GridViewRow row in grvExists.Rows)
        //    {
        //        if (row.RowType == DataControlRowType.DataRow)
        //        {
        //            row.Attributes["onmouseover"] =
        //               "this.style.cursor='pointer';";
        //            row.Attributes["onmouseout"] =
        //               "this.style.textDecoration='none';";
        //            row.Cells[1].Attributes["onclick"] =
        //             ClientScript.GetPostBackClientHyperlink(grvExists,
        //                "Select$" + row.DataItemIndex, true);
        //        }
        //    }

        //    base.Render(writer);
        //}
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToInt32(Session["role"]) != 1)
                {
                    Message("Bạn không đủ quyền để thực hiện chức năng này.");
                    Response.Redirect("Default.aspx");
                }

                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    var stafId = Convert.ToInt32(Request.QueryString["id"]);
                    if (_cache["Staff"] == null)
                    {
                        var lData = _loginController.GetAllUser();
                        if (lData.Any())
                        {
                            var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                            _cache.Set("Staff", lData.ToList(), policy);
                        }
                    }
                    var lData1 = (List<RelaxLoginsDataContract>)_cache["Staff"];
                    if (lData1 == null)
                        lData1 = new List<RelaxLoginsDataContract>();
                    var first = lData1.FirstOrDefault(p => p.StaffId == stafId);
                    if (first != null)
                        StaffId = first.Id;
                    else
                        StaffId = 0;
                }
                else
                    StaffId = 0;

                if (!IsPostBack)
                {
                    LoadGrandRole(StaffId);
                }
            }
            catch (Exception)
            {

            }
        }
        #endregion

        #region Event

        protected void grvnotmap_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "Select":
                        grvnotmap.SelectedIndex = int.Parse(e.CommandArgument.ToString());
                        grvnotmap.SelectedRow.CssClass = "forcolor";

                        var dgrSub = (GridView)grvnotmap.SelectedRow.FindControl("grvnotmapSub");
                        foreach (GridViewRow row in grvnotmap.Rows)
                        {
                            var check = (GridView)row.FindControl("grvnotmapSub");
                            if (check != null)
                                check.Visible = false;
                        }
                        if (dgrSub.Rows.Count > 0)
                            dgrSub.Visible = true;

                        break;
                    case "cmd_insert":
                        var ids = Convert.ToInt32(e.CommandArgument.ToString());
                        if (StaffId > 0)
                        {
                            var lPermision = new List<RelaxMenuMemberDataContract>();
                            var modulpermision = new RelaxMenuMemberDataContract
                            {
                                MenuId = ids,
                                MemberId = StaffId,
                                Active = 1
                            };
                            lPermision.Add(modulpermision);
                            //var dgrSubNot = (GridView)grvnotmap.SelectedRow.FindControl("grvnotmapSub");
                            //foreach (GridViewRow row in dgrSubNot.Rows)
                            //{
                            //    var chk = (CheckBox)row.FindControl("chkselect");
                            //    if (chk.Checked)
                            //    {
                            //        var mnuId = ((Label)row.FindControl("lblId")).Text;
                            //        var permis = new RelaxMenuMemberDataContract
                            //        {
                            //            MenuId = Convert.ToInt32(mnuId ?? "0"),
                            //            MemberId = StaffId,
                            //            Active = 1
                            //        };
                            //        lPermision.Add(permis);
                            //    }
                            //}
                            var lId = _menuMemberController.Add(lPermision);

                            for (var i = 0; i < lId.Count; i++)
                            {
                                lPermision[i].Id = lId[i];
                            }
                            var lStaffPermision = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
                            if (lStaffPermision == null)
                                lStaffPermision = new List<RelaxMenuMemberDataContract>();

                            lStaffPermision.AddRange(lPermision);

                            _cache["StaffMenu"] = lStaffPermision;

                            LoadGrandRole(StaffId);

                        }

                        break;

                }
            }
            catch (Exception)
            {

            }
        }

        protected void grvnotmap_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //try
            //{
            //    if (e.Row.RowType == DataControlRowType.DataRow)
            //    {
            //        var menuId = ((Label)e.Row.FindControl("lblId")).Text;
            //        var dgrnotmapSub = (GridView)e.Row.FindControl("grvnotmapSub");
            //        LoadSubmenuNotExists(Convert.ToInt32(menuId??"0"), StaffId, dgrnotmapSub);
            //        dgrnotmapSub.Visible = false;
            //    }
            //}
            //catch (Exception)
            //{

            //}
        }

        protected void grvExists_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "Select":
                        grvExists.SelectedIndex = Convert.ToInt32(e.CommandArgument);
                        grvExists.SelectedRow.CssClass = "forcolor";

                        //var dgrSub = (GridView)grvExists.SelectedRow.FindControl("grvExistsSub");
                        //foreach (GridViewRow row in grvExists.Rows)
                        //{
                        //    var check = (GridView)row.FindControl("grvExistsSub");
                        //    if (check != null)
                        //        check.Visible = false;
                        //}
                        //if (dgrSub.Rows.Count > 0)
                        //    dgrSub.Visible = true;

                        break;
                    case "cmd_Delete":
                        var ids = Convert.ToInt32(e.CommandArgument);
                        var lStaffPermision = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
                        var first = lStaffPermision.FirstOrDefault(p => p.Id == ids);
                        if (first != null)
                        {
                            _menuMemberController.Delete(new List<long> { first.Id });
                            lStaffPermision.Remove(first);
                            _cache["StaffMenu"] = lStaffPermision;
                            LoadGrandRole(StaffId);
                        }
                        break;
                    case "cmd_Active":
                        var id = Convert.ToInt32(e.CommandArgument);
                        var lStaffPermision1 = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
                        var first1 = lStaffPermision1.FirstOrDefault(p => p.Id == id);
                        if (first1 != null)
                        {
                            first1.Active = first1.Active == 1 ? 0 : 1;
                            if (_menuMemberController.Update(first1))
                            {
                                _cache["StaffMenu"] = lStaffPermision1;
                                LoadGrandRole(StaffId);
                            }
                        }
                        break;
                }
            }
            catch (Exception)
            {

            }
        }

        protected void grvExists_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    var menuId = ((Label)e.Row.FindControl("lblId")).Text;
            //    var dgrSubExists = (GridView)e.Row.FindControl("grvExistsSub");
            //    LoadSubmenuExists(Convert.ToInt32(menuId??"0"),StaffId, dgrSubExists);
            //    dgrSubExists.Visible = false;
            //}
        }
        protected void grvSubExists_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "cmd_DeleteSub":
                        var ids = Convert.ToInt32(e.CommandArgument);
                        var lStaffPermision = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
                        var first = lStaffPermision.FirstOrDefault(p => p.Id == ids);
                        if (first != null)
                        {
                            if (_menuMemberController.Delete(new List<long> { first.Id }))
                            {
                                lStaffPermision.Remove(first);
                                _cache["StaffMenu"] = lStaffPermision;
                                LoadGrandRole(StaffId);
                            }
                        }
                        break;
                }
            }
            catch (Exception)
            {

            }
        }
        #endregion

        #region Business

        private void LoadStaffMenu()
        {
            if (_cache["StaffMenu"] == null)
            {

                var lData = _menuMemberController.GetMenuMemberDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };

                    _cache.Set("StaffMenu", lData.ToList(), policy);
                }
            }
        }

        private void LoadMenu()
        {
            if (_cache["Menu"] == null)
            {
                var lData = _menuController.GetMenuDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };

                    _cache.Set("Menu", lData.ToList(), policy);
                }
            }
        }

        private void LoadGrandRole(long id = 0)
        {
            LoadStaffMenu();
            LoadMenu();

            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lMenuStaff = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
            if (lMenuStaff != null)
            {
                var existsmenu = (from menu in lMenu.Where(m => m.Languagecode == 1 && m.Type == 2)
                                  join staff in lMenuStaff.Where(p => p.MemberId == id) on menu.Id equals staff.MenuId
                                  select new RelaxMenuMemberDataContract
                                  {
                                      Id = staff.Id,
                                      MenuId = staff.MenuId,
                                      MemberId = staff.MemberId,
                                      MenuName = menu.Name,
                                      Active = staff.Active
                                  }).ToList();
                //var tmp = existsmenu.ToList();
                //foreach (var item in tmp)
                //{
                //    var checkItem = existsmenu.Where(p => p.Id == item.Id).ToList();
                //    if (checkItem.Count() > 1)
                //    {
                //        var first = checkItem.FirstOrDefault();
                //        foreach (var item1 in checkItem)
                //        {
                //            existsmenu.Remove(item1);
                //        }
                //        existsmenu.Add(first);
                //    }
                //}
                grvExists.DataSource = existsmenu;
                grvExists.DataBind();

                grvnotmap.DataSource = lMenu.Where(p => p.Languagecode == 1 && p.Parent == null && p.Type == 2 && !existsmenu.Select(s => s.MenuId).Contains(p.Id)).ToList();
                grvnotmap.DataBind();
            }
            else
            {
                grvnotmap.DataSource = lMenu.Where(m => m.Languagecode == 1 && m.Parent == null && m.Type == 2);
                grvnotmap.DataBind();
            }
        }

        private void LoadSubmenuNotExists(long id, long staffId, GridView grvView)
        {

            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lMenuStaff = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
            if (lMenuStaff != null)
            {
                var existsmenu = (from menu in lMenu.Where(m => m.Languagecode == 1 && m.Parent == Convert.ToString(id))
                                  join staff in lMenuStaff.Where(p => p.MemberId == staffId) on menu.Id equals staff.MenuId
                                  select new RelaxMenuMemberDataContract
                                  {
                                      Id = staff.Id,
                                      MenuId = staff.MenuId,
                                      MemberId = staff.MemberId,
                                      MenuName = menu.Name,
                                      Active = staff.Active
                                  }).ToList();

                grvView.DataSource = lMenu.Where(p => p.Languagecode == 1 && p.Parent == Convert.ToString(id) && !existsmenu.Select(s => s.MenuId).Contains(p.Id)).ToList();
                grvView.DataBind();
            }
            else
            {
                grvView.DataSource = lMenu.Where(m => m.Languagecode == 1 && m.Parent == Convert.ToString(id));
                grvView.DataBind();
            }
        }
        private void LoadSubmenuExists(long id, long staffId, GridView grvView)
        {

            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lMenuStaff = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
            if (lMenuStaff != null)
            {
                var existsmenu = (from menu in lMenu.Where(m => m.Languagecode == 1 && m.Parent == Convert.ToString(id))
                                  join staff in lMenuStaff.Where(p => p.MemberId == staffId) on menu.Id equals staff.MenuId
                                  select new RelaxMenuMemberDataContract
                                  {
                                      Id = staff.Id,
                                      MenuId = staff.MenuId,
                                      MemberId = staff.MemberId,
                                      MenuName = menu.Name,
                                      Active = staff.Active
                                  }).ToList();

                grvView.DataSource = existsmenu;
            }
            grvView.DataBind();
        }

        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion

       
    }
}